<template>
  <!-- 私信的对话框 -->
  <el-dialog
    v-model="dialogFormVisible"
    :close-on-click-modal="false"
    draggable
    :title="`发消息给 ${user?.name ? user?.name : '-'}`"
  >
    <el-form :model="form" :label-width="formLabelWidth">
      <el-form-item label="内容">
        <el-input
          type="textarea"
          :autosize="{ minRows: 3, maxRows: 5 }"
          v-model="form.msg"
          show-word-limit
          autocomplete="off"
          resize="none"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="onSendMsg(user.userId || user.id)"> 发送 </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { useWebsocketStore } from '@/store/websocket';
import { getLoginUserId } from '@/utils/storage';
import { ElMessage } from 'element-plus';
import { onBeforeUnmount, reactive, ref } from 'vue';
import { SIGNAL_TYPE_ONE_TO_ONE } from '@/constants/constants';

defineProps<{
  user: any;
}>();

// 私信对话框
const dialogFormVisible = ref(false);
const formLabelWidth = '80px';
const form = reactive({
  msg: '',
});

const websocketStore = useWebsocketStore();
function onSendMsg(remoteUid: string | number) {
  if (!form.msg.trim()) {
    return ElMessage({
      message: '消息内容不能为空',
      type: 'warning',
    });
  }
  // 发送信息
  const messageObj = {
    cmd: SIGNAL_TYPE_ONE_TO_ONE,
    remoteUid: remoteUid + '',
    msg: form.msg.trim(),
  };
  websocketStore.sendMessage(JSON.stringify(messageObj));
  websocketStore.websocket?.addEventListener('message', onMessage);
}
function onMessage(event: any) {
  const msg = JSON.parse(event.data);
  const sender = msg.remoteUid;
  if (
    msg.msg === form.msg.trim() &&
    msg.cmd === SIGNAL_TYPE_ONE_TO_ONE &&
    sender == getLoginUserId()
  ) {
    dialogFormVisible.value = false;
    ElMessage({
      message: '消息发送成功',
      type: 'success',
    });
    // 重置表单
    form.msg = '';
  }
}
onBeforeUnmount(() => {
  // 非聊天界面时，就不需要监听了
  websocketStore.websocket?.removeEventListener('message', onMessage);
});

defineExpose({
  dialogFormVisible,
});
</script>

<style lang="scss" scoped></style>
